<template>
  <div>
    <Modal
      v-model="isShowModal"
      :title="title"
      @on-cancel="hide('formValidate')"
      :mask-closable="false"
    >
      <Form
        ref="formValidate"
        :model="params"
        :rules="ruleValidate"
        label-position="top"
      >
        <FormItem label="分类图片：" prop="goodsTypePic">
          <div class="j-img-echo">
            <template v-if="!params.goodsTypePic">
              <Icon type="md-images" size="55" color="#c5c8ce" />
            </template>
            <template v-else>
              <img :src="params.goodsTypePic" />
            </template>
          </div>
          <Upload
            :action="action"
            :headers="headers"
            :show-upload-list="false"
            name="file"
            :on-success="uploadSuccess"
          >
            <Button icon="ios-cloud-upload-outline" style="width:488px">
              上传分类图片
            </Button>
          </Upload>
          <Alert show-icon closable style="margin-top:10px">
            建议上传122*122尺寸并且大小不能大于500kb的图片
          </Alert>
        </FormItem>
        <FormItem label="平台" prop="plantType">
          <Select
            placeholder="请选择平台"
            v-model="params.plantType"
            filterable
          >
            <Option
              v-for="(item, index) in platformList"
              :value="item.value"
              :key="index"
            >
              {{ item.label }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="小程序" prop="programId">
          <Select
            placeholder="请选择小程序"
            v-model="params.programId"
            filterable
          >
            <Option
              v-for="(item, index) in programList"
              :value="item.programId"
              :key="item.programId"
            >
              {{ item.programName }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="分类名称：" prop="goodsTypeName">
          <Input
            v-model.trim="params.goodsTypeName"
            placeholder="请输入分类名称"
          ></Input>
        </FormItem>
        <FormItem label="分类简介：" prop="goodsTypeIntro">
          <Input
            v-model.trim="params.goodsTypeIntro"
            placeholder="请输入分类简介"
          ></Input>
        </FormItem>
        <FormItem label="排序：" prop="sort">
          <Input
            v-model.trim="params.sort"
            placeholder="请输入分类排序"
            type="number"
          ></Input>
        </FormItem>
      </Form>

      <!-- 重写对话框底部按钮 -->
      <div slot="footer">
        <Button @click="hide('formValidate')">取消</Button>
        <Button
          v-if="type != 1"
          type="primary"
          @click="handleSubmit('formValidate')"
          :loading="loadingBtn"
        >
          <span v-if="!loadingBtn">确定</span>
          <span v-else>请稍候...</span>
        </Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import { platformList } from '@/constant/program';

  export default {
    name: 'type-ope',
    data() {
      return {
        platformList,
        allProgram: [],
        isShowModal: false,
        loadingBtn: false,
        usernameDis: false,
        title: '查看信息',
        type: 0,
        action: this.$uploadURL,
        headers: {
          token: JSON.parse(sessionStorage.getItem('J-TOKEN')).token
        },
        params: {
          goodsTypePic: '',
          goodsTypeName: '',
          goodsTypeIntro: '',
          level: '',
          parentTypeId: 0,
          sort: '999',
          goodsMallTypeId: '',
          programId: '',
          plantType: ''
        },
        ruleValidate: {
          goodsTypePic: [
            { required: true, message: '分类图片不能为空', trigger: 'change' }
          ],
          goodsTypeName: [
            { required: true, message: '分类名称不能为空', trigger: 'change' }
          ],
          sort: [
            { required: true, message: '排序不能为空', trigger: 'change' }
          ],
          plantType: [
            { required: true, message: '平台不能为空', trigger: 'change' }
          ],
          programId: [
            { required: true, message: '小程序不能为空', trigger: 'change' }
          ]
        }
      };
    },
    computed: {
      programList() {
        return this.allProgram
          .filter(item => item.platform == this.params.plantType)
          .map(item => ({ ...item, programId: item.programId.toString() }));
      }
    },
    methods: {
      queryAllProgram() {
        this.axios
          .post('/program/findList', { rows: 999, page: 1 })
          .then(res => {
            if (res.status == 200) {
              this.allProgram = res.data.rows;
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '查询小程序列表接口报错',
                duration: 0
              });
            }
          });
      },
      // 点击提交验证
      handleSubmit(name) {
        // console.log(this.params);
        this.$refs[name].validate(valid => {
          if (valid) {
            // this.$Message.error('验证通过');
            /**
             * type判断
             * 1.查看 2.新增 3.编辑
             */
            switch (this.type) {
              case 1:
                // this.title = '查看分类';
                break;
              case 2:
                // 新增分类
                this.addMallGoodsType();
                break;
              case 3:
                // 编辑分类
                this.updateMallGoodsType();
                break;
              default:
                this.$Notice.error({
                  title: '分类管理',
                  desc: '查看，新增，编辑区分判断报错',
                  duration: 0
                });
                break;
            }
          } else {
            this.$Message.error('还有信息没有填写合格哦~');
          }
        });
      },
      // 显示模态框
      show(type, row) {
        this.isShowModal = true;
        this.type = type;
        this.queryAllProgram();
        /**
         * type判断
         * 1.查看 2.新增 3.编辑
         */
        switch (type) {
          case 1:
            this.title = '查看分类';
            this.queryMallGoodsTypeInfo(row);
            break;
          case 2:
            this.title = '新增分类';
            if (row) {
              this.params.level = row.level + 1;
              this.params.parentTypeId = row.goodsMallTypeId;
            } else {
              this.params.level = 1;
              this.params.parentTypeId = 0;
            }
            break;
          case 3:
            this.title = '编辑分类';

            this.queryMallGoodsTypeInfo(row);
            break;
          default:
            this.$Notice.error({
              title: '分类管理',
              desc: '查看，新增，编辑模态框报错',
              duration: 0
            });
            break;
        }
      },
      // 新增分类
      addMallGoodsType() {
        this.$Spin.show();
        this.axios
          .post('/mallGoodsType/addMallGoodsType', this.params)
          .then(res => {
            setTimeout(() => {
              this.$Spin.hide();
            }, 300);
            if (res.status == 200) {
              this.$emit('changeDate');
              this.$Message.success('操作成功.');
              this.hide('formValidate');
            }
            if (res.status == 201) {
              this.$Message.error(res.msg);
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '新增分类接口报错',
                duration: 0
              });
            }
          });
      },
      // 编辑分类
      updateMallGoodsType() {
        console.log(this.params, 'params');
        this.$Spin.show();
        this.axios
          .post('/mallGoodsType/updateMallGoodsType', this.params)
          .then(res => {
            setTimeout(() => {
              this.$Spin.hide();
            }, 300);
            if (res.status == 200) {
              this.$emit('changeDate');
              this.$Message.success('操作成功.');
              this.hide('formValidate');
            }
            if (res.status == 201) {
              this.$Message.error(res.msg);
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '编辑分类接口报错',
                duration: 0
              });
            }
          });
      },
      // 查询分类详情
      queryMallGoodsTypeInfo(row) {
        this.$Spin.show();
        this.axios
          .post('/mallGoodsType/queryMallGoodsTypeInfo', {
            goodsMallTypeId: row.goodsMallTypeId
          })
          .then(res => {
            setTimeout(() => {
              this.$Spin.hide();
            }, 300);
            if (res.status == 200) {
              // this.$Message.success('操作成功.');
              this.params.goodsTypePic = res.data.goodsTypePic;
              this.params.goodsTypeName = res.data.goodsTypeName;
              this.params.goodsTypeIntro = res.data.goodsTypeIntro;
              this.params.level = res.data.level;
              this.params.parentTypeId = res.data.parentTypeId;
              this.params.goodsMallTypeId =
                res.data.goodsMallTypeId || row.goodsMallTypeId;
              this.params.plantType =
                res.data.plantType && res.data.plantType.toString();
              this.params.programId =
                res.data.programId && res.data.programId.toString();

              this.params.sort = res.data.sort && res.data.sort.toString();
              this.usernameDis = true;
              console.log('params', this.params);
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '查看分类详情接口报错',
                duration: 0
              });
            }
          });
      },
      // 上传成功
      uploadSuccess(response, file, fileList) {
        if (response.status == 200) {
          this.params.goodsTypePic = response.data;
        }
        if (response.status == 201) {
          this.$Message.error(response.msg);
        }
        if (response.status == 500) {
          this.$Notice.error({
            title: '服务器内部错误',
            desc: '上传banner接口报错',
            duration: 0
          });
        }
      },
      // 关闭模态框
      hide(name) {
        this.isShowModal = false;
        this.params.goodsMallTypeId = '';
        this.usernameDis = false;
        this.$refs[name].resetFields();
      }
    }
  };
</script>

<style scoped></style>
